package itstudio.instructor.adapter;

import itstudio.app.wq.R;
import itstudio.instructor.config.Config;
import itstudio.instructor.config.MyApplication;
import itstudio.instructor.entity.News;
import itstudio.instructor.fragment.FragmentCollect;
import itstudio.instructor.http.TwitterRestClient;
import itstudio.instructor.ui.NewsDetailActivity;
import itstudio.instructor.util.LoginUtil;
import itstudio.instructor.util.TimeUtil;
import itstudio.instructor.util.ToastUtil;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

public class CollectListAdapter extends BaseAdapter {
	
	/**
	 * 屏幕宽度,由于我们用的是HorizontalScrollView,所以按钮选项应该在屏幕外
	 */
	private Context context;
	private LayoutInflater mInflater;
	DisplayImageOptions options;
	private List<News> newsList =new ArrayList<News>();;
	private News news;
	private int mScreentWidth;
	private int downX = 0;
	private int upX = 0;
	private ImageLoader imageLoader = ImageLoader.getInstance();


	public CollectListAdapter(Context context, List<News> newsList,
			DisplayImageOptions options,int screenWidth) {
		if(newsList!=null){
			this.newsList = newsList;
		}
		this.context = context;
		this.mInflater = LayoutInflater.from(context);
		this.options = options;
		mScreentWidth = screenWidth;

	}

	@Override
	public int getCount() {
		return newsList==null? 0: newsList.size();
	}
	
	public void appendToList(List<News> lists) {

		if (lists == null) {
			return;
		}
		newsList.addAll(lists);
		notifyDataSetChanged();
	}
	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final ViewHolder holder;
		news = newsList.get(position);
		// 如果没有设置过,初始化convertView
		if (convertView == null) {
			// 获得设置的view
			holder=new ViewHolder();
			convertView = mInflater.inflate(
					R.layout.listitem_collect, null);
			holder.tvTitle = (TextView) convertView
					.findViewById(R.id.list_item_title);
			holder.tvContent = (TextView) convertView
					.findViewById(R.id.list_item_content);
			holder.tvTime = (TextView) convertView
					.findViewById(R.id.list_item_time);
			holder.ivAuthor=(ImageView) convertView.findViewById(R.id.list_item_img);
			holder.tvAuthor=(TextView) convertView.findViewById(R.id.list_item_author);

			// 初始化holder

			convertView.setTag(holder);
		} else// 有直接获得ViewHolder
		{
			holder = (ViewHolder) convertView.getTag();
		}

		holder.hSView = (HorizontalScrollView) convertView
				.findViewById(R.id.hsv);

		holder.action = convertView.findViewById(R.id.ll_action);
		holder.btTwo = (Button) convertView.findViewById(R.id.button2);
		holder.btTwo.setFocusable(false);

		// 把位置放到view中,这样点击事件就可以知道点击的是哪一条item
		holder.btTwo.setTag(position);

		holder.tvTitle.setText(news.getTitle());
		holder.tvContent.setText(news.getContent());
		holder.tvTime .setText(TimeUtil.dateToString(news.getPostTime(),TimeUtil.FORMAT_DATE));
		holder.tvAuthor.setText(news.getUser().getName());

		//给ImageView设置路径Tag,这是异步加载图片的小技巧
				convertView.setTag(holder);
				imageLoader.displayImage(Config.HEAD_URL+news.getUser().getHeadUrl(),holder.ivAuthor, options, new SimpleImageLoadingListener() {
							@Override
							public void onLoadingStarted(String imageUri, View view) {
								// holder.progressBar.setProgress(0);
								// holder.progressBar.setVisibility(View.VISIBLE);
							}

							@Override
							public void onLoadingFailed(String imageUri, View view,
									FailReason failReason) {
								// holder.progressBar.setVisibility(View.GONE);
							}

							@Override
							public void onLoadingComplete(String imageUri, View view,
									Bitmap loadedImage) {
								// holder.progressBar.setVisibility(View.GONE);
							}
						}, new ImageLoadingProgressListener() {
							@Override
							public void onProgressUpdate(String imageUri, View view,
									int current, int total) {
								// holder.progressBar.setProgress(Math.round(100.0f *
								// current / total));
							}
						});
		

		// 设置内容view的大小为屏幕宽度,这样按钮就正好被挤出屏幕外
		holder.content = convertView.findViewById(R.id.ll_content);
		LayoutParams lp = holder.content.getLayoutParams();
		lp.width = mScreentWidth;

		holder.btTwo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				cancelCollect(newsList.get(position).getId(),position);

			}
		});
		// 设置监听事件
		convertView.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {

				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					downX = (int) event.getX();
					break;
				case MotionEvent.ACTION_UP:
					upX = (int) event.getX();
					// 获得ViewHolder
					ViewHolder viewHolder = (ViewHolder) v.getTag();

					// 获得HorizontalScrollView滑动的水平方向值.
					int scrollX = viewHolder.hSView.getScrollX();

					// 获得操作区域的长度
					int actionW = viewHolder.action.getWidth();
					if (Math.abs(upX - downX) < 10) {
						holder.tvTitle.setTextColor(Color.GRAY);
						Intent intent = new Intent();
						intent.setClass(context, NewsDetailActivity.class);
						intent.putExtra("news", newsList.get(position));
						FragmentCollect.mactivity.startActivity(intent);

					}

					// 注意使用smoothScrollTo,这样效果看起来比较圆滑,不生硬
					// 如果水平方向的移动值<操作区域的长度的一半,就复原
					if (scrollX < actionW / 2) {
						viewHolder.hSView.smoothScrollTo(0, 0);
					} else// 否则的话显示操作区域
					{
						viewHolder.hSView.smoothScrollTo(actionW, 0);

					}
					return true;

				}
				return false;
			}
		});

		// 这里防止删除一条item后,ListView处于操作状态,直接还原
		if (holder.hSView.getScrollX() != 0) {
			holder.hSView.scrollTo(0, 0);
		}

		return convertView;
	}

	// 主要是避免了不断的view获取初始化.
	class ViewHolder {
		public HorizontalScrollView hSView;

		public View content;
		public TextView tvTitle;
		public TextView tvContent;
		public TextView tvTime;
		public ImageView ivAuthor;
		public TextView tvAuthor;
		public View action;
		public Button btTwo;
	}
	//添加收藏
	private void cancelCollect(int  newId,final int position){
		
		if(MyApplication.user==null){
			
			ToastUtil.showInfoMsg((Activity)context, R.string.please_login);
			return;
		}

		RequestParams params = new RequestParams();
		params.put("collect.news.id", newId);

		TwitterRestClient.post(Config.AC_COLLECT_CANCEL, params, new AsyncHttpResponseHandler(){
			
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				// TODO Auto-generated method stub
			}
			
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				
				String result = new String(arg2);
				
				if(result.indexOf(Config.SUCCESS)!=-1){
					newsList.remove(position);
					CollectListAdapter.this.notifyDataSetChanged();
				}
				if(result.indexOf(Config.LOGIN)!=-1){
					LoginUtil.Login(context);
				}
			}});
	}

}
